<template>
  <div class="user-container">
    <!--面包屑区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--card 区-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入用户名" v-model="queryObject.query" class="input-with-select" clearable
                    @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="openNewAddDialog">添加用户</el-button>
        </el-col>
      </el-row>

      <!--数据展示-->
      <el-table
        :data="userList"
        border
        stripe
        style="width: 100%">
        <el-table-column
          prop="username"
          label="#"
          type="index">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch @change="changeState(scope.row)"
                       v-model="scope.row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          width="300px"
          label="操作">
          <template slot-scope="scope">
            <!--修改-->
            <el-button type="primary" class="el-icon-edit" @click="openEditDialog(scope.row)" size="mini"></el-button>
            <!--删除-->
            <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <!--分配角色-->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" class="el-icon-setting"
                         @click="openAllocateDialog(scope.row)"
                         size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页去-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryObject.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryObject.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加用户对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%" @close="closeAddForm" :close-on-click-modal="false">
      <!--内容主体去-->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancleAddForm">取 消</el-button>
    <el-button type="primary" @click="submitAddForm">确 定</el-button>
  </span>
    </el-dialog>

    <!--添编辑用户对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%" @close="closeEditForm" :close-on-click-modal="false">
      <!--内容主体去-->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancleEditForm">取 消</el-button>
    <el-button type="primary" @click="submitEditForm">确 定</el-button>
  </span>
    </el-dialog>

    <!--分配角色-->
    <el-dialog
      title="分配角色"
      :visible.sync="allocateDialogVisible"
      @close="closeAllocateDialog"
      width="30%"
      >
      <el-form :model="allocateForm" ref="allocateFormRef">
        <el-form-item label="用户名">
          {{allocateForm.username}}
        </el-form-item>
        <el-form-item label="当前角色">
          {{allocateForm.currentRoleName}}
        </el-form-item>
        <el-form-item label="分配新角色">
          <el-select v-model="allocateForm.roleId" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id"
                       :value="item.id"
                       :label="item.roleName">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="allocateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allocateRole">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
    export default {
        data() {
            // 注意 自定义校验规则是存储在局部变量中
            // 校验邮箱
            let checkEmail = (rule, value, cb) => {
                const regEmail = /^\w+@\w+(\.\w+)+$/
                if (!regEmail.test(value)) {
                    return cb(new Error("请输入合法邮箱"))
                }
                cb()

            }
            // 校验手机号
            let checkMobile = (rule, value, cb) => {
                const regEmail = /^1[34578]\d{9}$/
                if (!regEmail.test(value)) {
                    return cb(new Error("请输入合法手机号"))
                }
                cb()
            }
            return {
                queryObject: {
                    query: '',
                    pagenum: 1,
                    pagesize: 5,
                },
                userList: [],
                total: 0,
                // 控制新增用户对话框的显示与隐藏
                addDialogVisible: false,
                // 控制修改用户对话框的显示与隐藏
                editDialogVisible: false,
                // 要添加的表单数据
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                // 编辑表单数据
                editForm: {},
                // 新增用户表单的校验规则
                addFormRules: {
                    username: [
                        {required: true, message: '用户名不能为空', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '密码不能为空', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '邮箱不能为空', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '手机号不能为空', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                },

                // 编辑用户表单的校验规则
                editFormRules: {
                    email: [
                        {required: true, message: '邮箱不能为空', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '手机号不能为空', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                },
                // 分配权限表单数据
                allocateForm: {
                    id: '',
                    username: '',
                    currentRoleName: '',
                    roleId: ''
                },
                // 分配权限对话显示与隐藏
                allocateDialogVisible: false,
                roleList: [],
            }
        },
        created() {
            this.getUserList();
        },
        methods: {
            async getUserList() {
                const {data: res} = await this.$http.get('/users', {params: this.queryObject});
                if (res.meta.status !== 200) {
                    return this.$message.error('用户信息获取失败')
                }
                this.userList = res.data.users
                this.total = res.data.total
                this.$message.success("用户列表获取成功")
            },
            handleSizeChange(newSize) {
                this.queryObject.pagesize = newSize
                this.getUserList()
            },
            handleCurrentChange(newCurrentPage) {
                this.queryObject.pagenum = newCurrentPage
                this.getUserList()
            },
            search() {
                this.getUserList()
            },
            async changeState(userinfo) {
                // const {data: res} = await this.$http.put('/users/' + uid + '/state/' + state)
                // console.log(`/users/${userinfo.id}/state/${userinfo.mg_state}`);
                const {data: res} = await this.$http.put(`/users/${userinfo.id}/state/${userinfo.mg_state}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('状态更改失败')
                }
                this.$message.success('状态更改成功')
            },
            cancleAddForm() {
                this.addDialogVisible = false
            },
            submitAddForm() {
                //校验参数
                this.$refs.addFormRef.validate(async (valid) => {
                    if (!valid) {
                        return this.$message.error('数据校验失败')
                    }
                    const {data: res} = await this.$http.post('/users', this.addForm);
                    if (res.meta.status !== 201) {
                        console.log(res.meta)
                        return this.$message.error('用户保存失败')
                    }
                    this.addDialogVisible = false
                    this.$message.success('用户添加成功')
                    this.getUserList()
                })
            },

            // 关闭添加用户对话框
            closeAddForm() {
                // 重置添加用户表单
                this.$refs.addFormRef.resetFields()
                this.addDialogVisible = false
            },
            // 关闭编辑用户对话框
            closeEditForm() {
                this.$refs.editFormRef.resetFields()
                this.editDialogVisible = false
            },

            // open 新增用户对话框
            openNewAddDialog() {
                this.addDialogVisible = true
            },
            // open 编辑用户对话框
            async openEditDialog(userInfo) {
                const {data: res} = await this.$http.get(`/users/${userInfo.id}`)
                if (res.meta.status !== 200) {
                    return this.$message.error("获取用户信息失败")
                } else {
                    console.log(res.data)
                    this.editForm = res.data
                    // let addForm = this.addForm;
                    // editForm.username = res.data.username
                    // editForm.email = res.data.email
                    // editForm.mobile = res.data.mobile
                    // editForm.id  = res.data.id
                    // console.log(this.addForm.mobile)
                    this.editDialogVisible = true
                }
            },
            cancleEditForm() {
                this.editDialogVisible = false;
            },
            submitEditForm() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return this.$message.error('数据校验不通过')
                    }
                    // const {data: res} = await this.$http.put(`/users/${this.editForm.id}`, this.editForm)
                    const {data: res} = await this.$http.put(`/users/${this.editForm.id}`, {
                        email: this.editForm.email,
                        mobile: this.editForm.mobile
                    })
                    if (res.meta.status !== 200) {
                        this.$message.error(res.meta.msg)
                    }
                    this.$message.success(res.meta.msg)
                    this.editDialogVisible = false
                    this.getUserList()
                })
            },
            // 删除用户
            async deleteUser(userId) {
                // promise方式
                /*this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await this.$http.delete(`/users/${userId}`)
                    if (res.meta.status !== 200) {
                        return this.$message.error(res.meta.msg)
                    }
                    this.getUserList()
                    this.$message.success(res.meta.msg)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '删除已取消删除'
                    });
                });*/
                const confirmRes = await this.$confirm('是否确认删除用户', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                // 如果确认 返回confirm
                // 如果取消 返回cancel
                console.log(confirmRes)
                if (confirmRes !== 'confirm') {
                    return this.$message.info('已经取消删除')
                }
                this.$http.delete(`/users/${userId}`).then(res => {
                    if (res.data.meta.status !== 200) {
                        return this.$message.error(res.data.meta.msg)
                    }
                    this.getUserList()
                    this.$message.success('删除成功')
                }).catch(err => err)

            },
            async openAllocateDialog(userInfo) {
                this.allocateForm.username = userInfo.username
                this.allocateForm.currentRoleName = userInfo.role_name
                this.allocateForm.id = userInfo.id
                // 获取角色列表
                const {data: res} = await this.$http.get('/roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取权限列表失败')
                }
                this.roleList = res.data
                // 显示分配权限对话框
                this.allocateDialogVisible = true
            },
            // 分配角色
            async allocateRole() {
                if (!this.allocateForm.roleId) {
                    return this.$message.error('请选择角色')
                }
                const {data: res} = await this.$http.put(`/users/${this.allocateForm.id}/role`, {rid:
                    this.allocateForm.roleId})
                console.log(res)
                if (res.meta.status !== 200) {
                    return this.$message.error('分配角色失败')
                }
                this.$message.success('分配角色成功')
                this.getUserList()
                this.allocateDialogVisible = false
            },
            closeAllocateDialog() {
                this.allocateForm.roleId = ''
            }

        },

    }
</script>

<style scoped>

</style>
